<template>
  <div>
    <div style="background-color: #fefefe;">
      <el-form label-width="" size="mini">
        <el-row :gutter="20">
          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">日期区间:</div>
            <el-date-picker type="daterange" v-model="filterData.daterange" clearable start-placeholder="起始日期"
              end-placeholder="结束日期" value-format="yyyy-MM-dd" range-separator="至" style="width: 100%;">
            </el-date-picker>
          </el-col>

          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">发票号码:</div>
            <el-input placeholder="发票号码或数量发票号" v-model="filterData.num" clearable></el-input>
          </el-col>

          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">开票名称:</div>
            <el-input placeholder="税收分类或货物服务名称" v-model="filterData.good" clearable></el-input>
          </el-col>

          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">价税总额:</div>
            <el-input placeholder="票面价税总额" v-model="filterData.sum" clearable></el-input>
          </el-col>

          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">销方名称:</div>
            <el-select v-model="filterData.seller" filterable style="width: 100%;" clearable placeholder="销售企业名称" allow-create
              filterable>
              <el-option v-for="(item,index) in sellerlist" :label="item.title" :key="item.index" :value="item.title">
              </el-option>
            </el-select>
          </el-col>
          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">采购单号:</div>
            <el-input placeholder="关联采购单号" v-model="filterData.bind_buyreqcode" clearable></el-input>
          </el-col>

          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">销项票号:</div>
            <el-input placeholder="关联销项发票号码" v-model="filterData.bind_saleticketnum" clearable></el-input>
          </el-col>

          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">采购核销:</div>
            <el-select v-model="filterData.buy_bindstatus" placeholder="采购核销" style="width: 100%;" clearable>
              <el-option label="未核销" value="0"></el-option>
              <el-option label="已核销" value="1"></el-option>
              <el-option label="部分核销" value="2"></el-option>
            </el-select>
          </el-col>

          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">销售状态:</div>
            <el-select v-model="filterData.sale_bindstatus" placeholder="销售状态" style="width: 100%;" clearable>
              <el-option label="未售" value="0"></el-option>
              <el-option label="已售" value="1"></el-option>
            </el-select>
          </el-col>



          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">所属账套:</div>
            <el-select v-model="filterData.buyer" filterable placeholder="账套" style="width: 100%;" clearable>
              <el-option :label="item.name" :value="item.name" v-for="(item,index) in accounts"
                :key="index"></el-option>
            </el-select>
          </el-col>

          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">发票用途</div>
            <el-select v-model="filterData.usage" placeholder="发票用途" style="width: 100%;" clearable allow-create
              filterable>
              <el-option label="物资发票" value="物资发票"></el-option>
              <el-option label="费用发票" value="费用发票"></el-option>
            </el-select>
          </el-col>

          <el-col style="width: 280px;" class="labelitem">
            <div style="width: 80px;">发票备注:</div>
            <el-input placeholder="发票备注" v-model="filterData.memo" clearable></el-input>
          </el-col>

          <el-col style="width: 280px;" class="labelitem">
            <el-form-item label="" style="text-align: right;">
              <el-button type="primary" icon="el-icon-search" @click="curpage=1;loadDataList()">查询发票</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div style="padding: 5px;display: flex;">
      <div style="flex: 1;">
        <el-button-group>
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleCreate">手动录入发票</el-button>
        </el-button-group>
      </div>
      <div><el-button type="primary" size="mini" icon="el-icon-download" @click="handleExport">
          {{selection.length>0? '导出选中项':"导出全部"}}
        </el-button></div>
    </div>
    <el-drawer title="发票明细" direction="ttb" :visible.sync="drawerVisible" style="height: 1500px;">
      <div style="padding: 0px 30px;">
        <div style="height: 200px; border: 1px solid #efefef;" v-if="!currentRow"></div>
        <div style="height: 200px;" v-if="currentRow">
          <div style="text-align: center;font-size: 16px;font-weight: bold;">{{currentRow.type}}</div>
          <div style="text-align: center;">({{currentRow.usage}})</div>
          <div style="height: 60px;">
            <el-col :span="8">
              <div style="padding-top: 30px;padding-left: 10px;"><span>购买方:{{currentRow.buyer}}</span></div>
            </el-col>
            <el-col :span="9">
              <div style="padding-top: 30px;"><span>销售方:{{currentRow.seller}}</span></div>
            </el-col>
            <el-col :span="7" style="text-align: right;padding-right: 5px;">
              <div style="width: 190px;text-align: left;">发票号码:{{currentRow.num}}</div>
              <div style="width: 190px; text-align: left;">发票代码:{{currentRow.code}}</div>
              <div style="width: 190px;text-align: left;">开票日期:{{currentRow.date}}</div>
            </el-col>
          </div>
          <div style="background-color: #dddddd; height: 200px; overflow-y: auto;clear: both;">
            <el-table v-if="currentRow" :data="currentRow.goods" border width="100%" height="100%">
              <el-table-column label="序号" type="index" align="center"></el-table-column>
              <el-table-column label="税收类目及名称" prop="taxname" width="150px" show-overflow-tooltip>
                <template v-slot="scope">
                  *{{scope.row.taxname}}*{{scope.row.title}}
                </template>
              </el-table-column>
              <el-table-column label="规格" prop="model" show-overflow-tooltip></el-table-column>
              <el-table-column label="单位" prop="unit" width="60" show-overflow-tooltip align="center">
              </el-table-column>
              <el-table-column label="数量" prop="count" width="60" align="center"></el-table-column>
              <el-table-column label="单价" prop="price" width="120px" show-overflow-tooltip></el-table-column>
              <el-table-column label="金额" prop="total" align="center"></el-table-column>
              <el-table-column label="税率" prop="rate" width="60" align="center">
                <template v-slot="scope">
                  {{scope.row.rate*100}}%
                </template>
              </el-table-column>
              <el-table-column label="税额" prop="tax" align="center"></el-table-column>
              <el-table-column label="价税合计" prop="sum" align="center"></el-table-column>
            </el-table>
          </div>
          <div style="display: flex;">
            <div style="flex:1;line-height: 35px; height:35px">备注:{{currentRow.memo}}</div>
            <div style="text-align: right; line-height: 35px; height:35px">
              <span style="margin-right: 15px;">金额: {{DNumber(currentRow.total,2)}}</span>
              <span style="margin-right: 15px;">税额: {{DNumber(currentRow.tax,2)}}</span>
              <span style="margin-right: 15px;">合计: {{DNumber(currentRow.sum,2)}}</span>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
    <div>
      <div style="height: 600px;overflow-y: auto;">
        <el-table border :data="tableData" style="width: 100%;" height="100%" highlight-current-row
          @row-click="handleTicketRowClick" empty-text="暂无发票或未查询到相关发票信息" @row-dblclick="handleDoubleClick"
          @selection-change="handleSelection">
          <el-table-column label="" type="selection" align="center" fixed="left"></el-table-column>
          <el-table-column label="序号" type="index" align="center"></el-table-column>
          <el-table-column label="详情" type="expand">
            <template v-slot="scope">
              <div style="padding-left: 100px; width: 1200px;">
                <el-table :data="scope.row.goods" border>
                  <el-table-column label="序号" type="index" align="center"></el-table-column>
                  <el-table-column label="货物或税收名称" prop="title" width="250px" show-overflow-tooltip>
                    <template v-slot="scope1">
                      * {{scope1.row.taxname}} * {{scope1.row.title}}
                    </template>
                  </el-table-column>
                  <el-table-column label="规格型号" prop="model" show-overflow-tooltip></el-table-column>
                  <el-table-column label="单位" prop="unit" width="90px" align="center"></el-table-column>
                  <el-table-column label="数量" prop="count" width="90px" align="center"></el-table-column>
                  <el-table-column label="单价" prop="price" width="120px" align="center"></el-table-column>
                  <el-table-column label="金额" prop="total" width="120px" align="center"></el-table-column>
                  <el-table-column label="税率" prop="rate" width="60px" align="center"></el-table-column>
                  <el-table-column label="税额" prop="tax" width="80px" align="center"></el-table-column>
                  <el-table-column label="价税总额" prop="sum" width="120px" align="center"></el-table-column>
                </el-table>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="开票日期" prop="date" width="140px" align="center"></el-table-column>
          <el-table-column label="发票号码" prop="num" width="160px"></el-table-column>
          <el-table-column label="销方单位" prop="seller" width="150px" show-overflow-tooltip></el-table-column>
          <el-table-column label="发票类型" prop="type" width="110px" align="center"></el-table-column>
          <el-table-column label="金额" prop="total" width="100px" align="center"></el-table-column>
          <el-table-column label="税额" prop="tax" width="100px" align="center"></el-table-column>
          <el-table-column label="税价总额" prop="sum" width="110px" align="center"></el-table-column>
           <el-table-column label="发票用途" prop="usage" width="80px" align="center"></el-table-column>
          <el-table-column label="发票备注" prop="memo" show-overflow-tooltip></el-table-column>

          <el-table-column label="采购状态" width="100px" align="center">
            <el-table-column label="核销状态" align="center" width="80px">
              <template v-slot="scope">
                <span v-if="scope.row.buy_bindstatus==0" style="color:#ff5500;">未核销</span>
                <span v-if="scope.row.buy_bindstatus==1" style="color:#00bc00;">已核销</span>
                <span v-if="scope.row.buy_bindstatus==2" style="color:darkgoldenrod">部分核销</span>
              </template>
            </el-table-column>
            <el-table-column label="关联采购单号" show-overflow-tooltip width="120px" align="center"
              prop="buy_bindnums"></el-table-column>
          </el-table-column>
          <el-table-column label="销售状态" prop="saleticket_bindstatus1" align="center">
            <el-table-column label="销售状态" align="center" width="80px">
              <template v-slot="scope">
                <span v-if="scope.row.saleticket_bindstatus1==1" style="color: #00bc00;">已售</span>
                <span v-if="scope.row.saleticket_bindstatus1==0" style="color:#ff5500">未售</span>
              </template>
            </el-table-column>
            <el-table-column label="关联销项票号" prop="saleticket_bindnum1" show-overflow-tooltip width="120px"
              align="center"></el-table-column>
          </el-table-column>
          <el-table-column label="购方单位" prop="buyer" show-overflow-tooltip></el-table-column>
          <el-table-column label="操作" width="120px" align="center" fixed="right">
            <template v-slot="scope">
              <el-button-group>
                <el-button type="primary" icon="el-icon-edit-outline" size="mini" circle
                  @click="handleEdit(scope.$index,scope.row)"></el-button>
                <el-button size="mini" v-if="scope.row.attach.length>0" circle icon="el-icon-link" title="查看附件"
                  @click="handleViewAttach(scope.$index,scope.row)"></el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" circle
                  @click="handleDelete(scope.$index,scope.row)"></el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="display: flex;">
        <div style="flex: 1; line-height: 30px;display: flex;">
          <div style="width: 150px;">金额:{{parseFloat(sumtotal).toFixed(4)}}</div>
          <div style="width: 150px;">税额:{{parseFloat(sumtax).toFixed(4)}}</div>
          <div style="width: 150px;">价税总额:{{parseFloat(sumall).toFixed(4)}}</div>
          <div style="width: 150px;">价税总额:{{parseFloat(sumpage).toFixed(4)}}</div>
           <div style="width: 150px;">选中金额:{{parseFloat(sumtotal_selection).toFixed(4)}}</div>
           <div style="width: 150px;">选中税额:{{parseFloat(sumtax_selection).toFixed(4)}}</div>
          <div style="width: 150px;">选中价税总额:{{parseFloat(sumselection).toFixed(4)}}</div>
        </div>
        <div style="text-align: right;">
          <el-pagination layout=" prev, pager,next,sizes,total" :total="numrows" :page-size="pagesize"
            :current-page="curpage" prev-text="上一页" next-text="下一页" :page-sizes="[15, 30, 50]"
            @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
        </div>
      </div>
    </div>

    <div>
      <el-row :gutter="20">
        <el-col :span="12" v-if="false">
          <div style="display: flex;">
            <div style="flex: 1;">
              <div class="title">发票明细</div>
            </div>
            <div style="display: flex">
              <el-button @click="handleViewAttach" type="primary" v-if="currentRow && currentRow.attach.length>0"
                size="mini">查看附件</el-button>
            </div>
          </div>
          <div style="height: 200px; border: 1px solid #efefef;" v-if="!currentRow"></div>
          <div style="height: 200px; border: 1px solid #efefef;" v-if="currentRow">
            <div style="text-align: center;font-size: 16px;font-weight: bold;">{{currentRow.type}}</div>
            <div style="height: 60px;">
              <el-col :span="8">
                <div style="padding-top: 30px;padding-left: 10px;"><span>购买方:{{currentRow.buyer}}</span></div>
              </el-col>
              <el-col :span="9">
                <div style="padding-top: 30px;"><span>销售方:{{currentRow.seller}}</span></div>
              </el-col>
              <el-col :span="7" style="text-align: right;padding-right: 5px;">
                <div style="width: 190px;text-align: left;">发票号码:{{currentRow.num}}</div>
                <div style="width: 190px; text-align: left;">发票代码:{{currentRow.code}}</div>
                <div style="width: 190px;text-align: left;">开票日期:{{currentRow.date}}</div>
              </el-col>
            </div>
            <div style="background-color: #dddddd; height: 200px; overflow-y: auto;clear: both;">
              <el-table v-if="currentRow" :data="currentRow.goods" border width="100%" height="100%">
                <el-table-column label="序号" type="index" align="center"></el-table-column>
                <el-table-column label="税收类目及名称" prop="taxname" width="150px" show-overflow-tooltip>
                  <template v-slot="scope">
                    *{{scope.row.taxname}}*{{scope.row.title}}
                  </template>
                </el-table-column>
                <el-table-column label="规格" prop="model" show-overflow-tooltip></el-table-column>
                <el-table-column label="单位" prop="unit" width="60" show-overflow-tooltip align="center">
                </el-table-column>
                <el-table-column label="数量" prop="count" width="60" align="center"></el-table-column>
                <el-table-column label="单价" prop="price" width="120px" show-overflow-tooltip></el-table-column>
                <el-table-column label="金额" prop="total" align="center"></el-table-column>
                <el-table-column label="税率" prop="rate" width="60" align="center">
                  <template v-slot="scope">
                    {{scope.row.rate*100}}%
                  </template>
                </el-table-column>
                <el-table-column label="税额" prop="tax" align="center"></el-table-column>
                <el-table-column label="价税合计" prop="sum" align="center"></el-table-column>
              </el-table>
            </div>
            <div style="display: flex;">
              <div style="flex:1;line-height: 35px; height:35px">备注:{{currentRow.memo}}</div>
              <div style="text-align: right; line-height: 35px; height:35px">
                <span style="margin-right: 15px;">金额: {{DNumber(currentRow.total,2)}}</span>
                <span style="margin-right: 15px;">税额: {{DNumber(currentRow.tax,2)}}</span>
                <span style="margin-right: 15px;">合计: {{DNumber(currentRow.sum,2)}}</span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="title">已关联采购单号</div>
          <div>
            <span v-if="currentRow">{{currentRow.buy_bindnums}}</span>
          </div>
        </el-col>
      </el-row>
    </div>

    <CreateUI ref="createUI" v-if="createVisible" @completeHandler="handleCreateCallback"></CreateUI>
    <EditUI ref="editUI" v-if="editVisible" @completeHandler="handleEditCallback"></EditUI>
    <AttachUI ref="attachUI" v-if="attachVisible"></AttachUI>
  </div>
  </div>
</template>

<script>
  import CreateUI from './create.vue';
  import EditUI from './edit.vue'
  import AttachUI from '@/components/attachviewer.vue'
  export default {
    components: {
      CreateUI,
      EditUI,
      AttachUI
    },
    data() {
      return {
        drawerVisible: false,
        filterData: {
          seller: '',
          buyer: '',
          num: '',
          good: '',
          sum: '',
          daterange: '',
          buy_bindstatus: "",
          sale_bindstatus: "",
          memo: '',
          bind_buyreqcode:'',
          bind_saleticketnum:'',
          usage: ''
        },
        accounts: [],
        sumall: 0,
        sumpage: 0,
        sumselection: 0,
        sumtotal_selection:0,
        sumtax_selection:0,
        sumtotal:0,
        sumtax:0,
        list: [],
        numrows: 1,
        pagesize: 15,
        curpage: 1,
        curdata: {
          id: '',
          name: '',
          type: '',
          url: ''
        },
        selection: [],
        sellerlist: [],
        buyerlist: [],
        currentRow: null,
        tableData: [],
        createVisible: false,
        editVisible: false,
        attachVisible: false
      }
    },
    created() {

      var now= new Date();
      var firstDay=this.formatDate(new Date(now.getFullYear(),now.getMonth(),1));
      var lastDay=this.formatDate(new Date(now.getFullYear(),now.getMonth()+1,0));
      this.filterData.daterange = [firstDay,lastDay];



      this.loadSellers();
      this.loadBuyers();
      this.loadDataList();
      this.loadAccount();
    },
    methods: {
      formatDate(date) {
        const yyyy = date.getFullYear();
        const mm = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
        const dd = String(date.getDate()).padStart(2, '0');
        return `${yyyy}-${mm}-${dd}`;
      },
      handleSelection(list) {
        this.selection = list;
        this.sumselection = 0;
        this.sumtax_selection=0;
        this.sumtotal_selection=0;
        this.selection.forEach((item) => {
          this.sumselection += parseFloat(item.sum);
           this.sumtax_selection += parseFloat(item.tax);
           this.sumtotal_selection+=parseFloat(item.total);
        })


      },
      handleDoubleClick(row, column, event) {
        this.drawerVisible = true;
      },
      loadAccount() {
        this.axios.post("api/admin/account/list").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.accounts = res.data.list;
          }
        })
      },
      handleExport() {
        if (this.selection.length > 0) {
          //导出选中
          var index = 1;
          let slist = this.selection.map((item) => {
            let obj = {
              "序号": index,
              "开票日期": item.date,
              "发票号码": item.fphm,
              "销方单位": item.seller,
              "发票类型": item.tickettype,
              "金额": item.total,
              "税额": item.tax,
              "价税总额": item.sum,
              "采购核销状态": item.buy_bindstatus == 1 ? "已核销" : "未核销",
              "关联采购单号": item.buy_bindcode,
              "销售状态": item.sale_bindstatus == 1 ? "已售" : "未售",
              "关联销项票号": item.saleticket_bindnum1,
              "发票备注": item.memo,
              "购方单位": item.buyer,
            }
            index++;
            return obj;
          });
          let ws = XLSX.utils.json_to_sheet(slist, {
            skipHeader: false
          });
          ws["!cols"] = [{
            wpx: 80
          }];
          let wb = XLSX.utils.book_new();
          XLSX.utils.book_append_sheet(wb, ws, '进项发票');
          XLSX.writeFile(wb, "进项发票列表.xlsx");
        }


      },
      loadBuyers() {
        this.axios.post("api/admin/supplier/list").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.buyerlist = res.data.list;
          }
        });
      },
      loadSellers() {
        this.axios.post("api/admin/buysupplier/list_item").then(res => {
          if (res.status == 200 && res.data.code == 0) {
            this.sellerlist = res.data.list;
          }
        });
      },
      handleTicketRowClick(row, column, event) {
        this.currentRow = row;
        this.list = row.attach;
        if (this.list.length > 0) {
          this.cur = 0;
          this.curdata = this.list[this.cur];
        } else {
          this.cur = -1;
          this.curdata = {
            type: '-1',
            url: '',
            attach: []
          };
        }
      },
      handleSizeChange: function(val) {
        this.pagesize = val;
        this.curpage = 1;
        this.loadDataList();
      },
      handleCurrentChange: function(val) {
        this.curpage = parseInt(val);
        this.loadDataList();
      },
      loadDataList() {
        var params = {
          daterange: this.filterData.daterange,
          seller: this.filterData.seller,
          buyer: this.filterData.buyer,
          num: this.filterData.num,
          sum: this.filterData.sum,
          good: this.filterData.good,
          curpage: this.curpage,
          pagesize: this.pagesize,
          buy_bindstatus: this.filterData.buy_bindstatus,
          sale_bindstatus: this.filterData.sale_bindstatus,
          delivercode: this.filterData.delivercode,
          usage: this.filterData.usage,
          memo: this.filterData.memo,
          bind_buyreqcode:this.filterData.bind_buyreqcode,
          bind_saleticketnum:this.filterData.bind_saleticketnum
        }
        this.axios.post("api/admin/buyticket/list", params).then((res) => {
          if (res.status == 200 && res.data.code) {
            this.tableData = res.data.list;
            this.numrows = res.data.numrows;
            this.sumall = res.data.sumall;
            this.sumtotal=res.data.sumtotal;
            this.sumtax=res.data.sumtax;
            if (this.tableData.length > 0) {
              this.currentRow = this.tableData[0];
            }
            this.sumpage = 0;
            this.tableData.forEach((item) => {
              this.sumpage += parseFloat(item.sum);
            })


          }
        });
      },
      handleEditCallback(index, data, attachlist) {
        this.tableData[index].attach = attachlist;
        this.currentRow = this.tableData[index];
        this.tableData[index].num = data.num;
        this.tableData[index].seller = data.seller;
        this.tableData[index].buyer = data.buyer;
        this.tableData[index].type = data.type;
        this.tableData[index].sum = data.sum;
        this.tableData[index].tax = data.tax;
        this.tableData[index].date = data.date;
        this.tableData[index].usage=data.usage;

      },
      handleViewAttach(index, row) { //预览附件
        this.currentRow = row;
        this.attachVisible = true;
        this.$nextTick(() => {
          this.$refs.attachUI.dialogVisible = true;
          this.$refs.attachUI.initData(this.currentRow.attach);
        })
      },
      handleDelete(index, row) {
        let confirmText = ["发票号或数电票号: " + row.num, "收票方:" + row.buyer, "发票总额:" + row.sum, "开票方: " + row.seller];
        const newDatas = [];
        const h = this.$createElement;
        for (const i in confirmText) {
          newDatas.push(h('p', null, confirmText[i]));
        }
        this.$confirm('标题', "确定要删除以下联系人吗？", {
          message: h('div', null, newDatas),
          confirmButtonText: "删除",
          cancelButtonText: "取消",
          type: 'error'
        }).then(() => {
          this.axios.post("api/admin/buyticket/remove", {
            id: row.id,
            num: row.num
          }).then(res => {
            this.$message.success(res.data.msg);
            if (res.status == 200 && res.data.code == 1) {
              this.loadDataList();
            }
          })
        });
      },
      handleCreate() {
        this.createVisible = true;
        this.$nextTick(() => {
          this.$refs.createUI.dialogVisible = true;
          this.$refs.createUI.init();
        })
      },
      handleCreateCallback() {
        this.loadDataList();
      },
      handleEdit(index, data) {
        this.editVisible = true;
        this.$nextTick(() => {
          this.$refs.editUI.dialogVisible = true;
          this.$refs.editUI.init(index, JSON.parse(JSON.stringify(data)));
        })
      }
    }
  }
</script>

<style scoped>
  .labelitem {
    display: flex;
    line-height: 30px;
  }
</style>
